using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using Helpers;


namespace HttpRequester.RequestMakers.Base
{
    public class RequestManagerPlaneHtml : RequestManagerBase
    {
        public RequestManagerPlaneHtml()
            : base()
        { }

        public string PageContent { get; protected set; }

        public override void ProcessResponse(HttpWebResponse response)
        {
            PageContent = ReadResponseContent(response);
        }

        protected string ReadResponseContent(HttpWebResponse response)
        {
            if (response == null)
                return null;

            string result = null;
            Stream streamResponse = null;
            StreamReader streamRead = null;

            try
            {
                streamResponse = response.GetResponseStream();
                streamRead = new StreamReader(streamResponse, Encoding.GetEncoding("windows-1251"));

                char[] readBuff = new char[256];
                StringBuilder content = new StringBuilder();
                int count = streamRead.Read(readBuff, 0, readBuff.Length);

                while (count > 0)
                {
                    content.Append(readBuff, 0, count);
                    count = streamRead.Read(readBuff, 0, readBuff.Length);
                }

                result = content.ToString();
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex.Message);
            }
            finally
            {
                if (streamResponse != null)
                    streamResponse.Close();
                if (streamRead != null)
                    streamRead.Close();
            }

            return result;
        }

        public override void SaveResponseContent(string fileName)
        {
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(fileName);
                sw.WriteLine(PageContent);
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex.Message);
            }
            finally
            {
                if (sw != null)
                    sw.Close();
            }
        }
    }
}
